package com.third.clock.manager;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;

import com.amap.api.location.AMapLocation;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;
import com.third.clock.ui.OnePiexlActivity;
import com.third.clock.bean.LoginEntity;
import com.third.clock.common.ConfigureLog4JUtil;
import com.third.clock.common.Contants;
import com.third.clock.common.GPSUtil;
import com.third.clock.common.LogUtils;
import com.third.clock.receiver.SystemBroadcastReceiver;

import java.lang.reflect.Method;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import static com.third.clock.common.Contants.ACTION_RTC_HEART;
import static com.third.clock.common.Contants.ACTION_RTC_LOCATION;

/**
 * Created by Administrator on 2018/7/21 0021.
 */

public class TimerManager implements IBaseManager{

    public static final String TAG="TimerManager";

    private Context mContext;

    private AlarmManager alarmManager;

    private ClockManager mClockManager;

    private PowerManager.WakeLock mWakeLock;

    private AlarmBroadcastReceiver mAlarmBroadcastReceiver;

    public  int RTC_HEART=3;

    //毫秒值 1000*60*1
    public  long RTC_LOCATION=1000*60*1;

    public TimerManager(Context context,ClockManager mClockManager){
        this.mContext=context;
        this.mClockManager=mClockManager;
    }


    @Override
    public void onCreate() {
        alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
        SystemBroadcastReceiver.setObserve(onSystemBroadcastReceiverObserve);
        registerReceiver();
    }

    @Override
    public void onDestroy() {
        handler.removeCallbacksAndMessages(null);
        SystemBroadcastReceiver.setObserve(null);
        unregisterReceiver();
    }

    private Handler handler=new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String action= (String) msg.obj;
            if(action==null) return ;

            if(action.equals(ACTION_RTC_LOCATION)){
                startAlarm(mContext,ACTION_RTC_LOCATION,Contants.PENDINGINTENT_LOCATION,RTC_LOCATION);
                Logger.d("TimerManager  ACTION_RTC_LOCATION");
                postLocation();
                acquireWakeLock();
            }else if(action.equals(ACTION_RTC_HEART)){
                startAlarm(mContext,ACTION_RTC_HEART,Contants.PENDINGINTENT_HEART,RTC_HEART);
                Logger.d("TimerManager  ACTION_RTC_HEART");

            }
        }
    };


    public void startAlarm(Context context, String action,int requestCode, long timeinmillis){
        Intent intent = new Intent();
        intent.setClassName("com.third.clock", "com.third.clock.receiver.SystemBroadcastReceiver");
        intent.setAction(action);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context,requestCode,intent,0);
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        if (Build.VERSION.SDK_INT >= 23) {
            alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,
                    calendar.getTimeInMillis()+timeinmillis, pendingIntent);
        }else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis()+timeinmillis, pendingIntent);
        } else {
            alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis()+timeinmillis,pendingIntent);
        }

    }


    private SystemBroadcastReceiver.onSystemBroadcastReceiverObserve onSystemBroadcastReceiverObserve=new SystemBroadcastReceiver.onSystemBroadcastReceiverObserve(){
        @Override
        public void onEvent(Intent intent) {
           if(intent==null) return;
           if(intent.getAction()==null) return;
           if(handler!=null){
               Message message=handler.obtainMessage();
               message.obj=intent.getAction();
               message.sendToTarget();

           }

        }
    };

    private void postLocation(){
       if(mClockManager!=null){
           LocationManager mLocationManager= mClockManager.getLocationManager();
           OkHttpClientManager okHttpClientManager= mClockManager.getOkHttpClientManager();
           if(mLocationManager!=null&&okHttpClientManager!=null){
               AMapLocation mAMapLocation=mLocationManager.getAMapLocation();
               Map<String,Object> locationMap=new HashMap<>();
               if(mClockManager.mLoginResponseData!=null&&mClockManager.mLoginResponseData.getData()!=null){
                   LoginEntity entity=mClockManager.mLoginResponseData.getData();
                   if(entity.getMobile()!=null) {
                       locationMap.put("mobile", entity.getMobile());
                   }
               }
               if(mAMapLocation!=null){
                   if (mAMapLocation.getErrorCode() == 0) {
                       //定位成功回调信息，设置相关消息
                       //坐标转换，gcj02-84
//                       Map<String,Double> formatLocation= GCJ02ToWGS84Util.gcj2wgs(mAMapLocation.getLongitude(),mAMapLocation.getLatitude());
//                       Double longitude=formatLocation.get("lon");
//                       Double latitude=formatLocation.get("lat");
                       double[] doubles84= GPSUtil.gcj02_To_Gps84(mAMapLocation.getLatitude(),mAMapLocation.getLongitude());
                       locationMap.put("longitude", doubles84[1]);
                       locationMap.put("latitude", doubles84[0]);
                   }else{
                       locationMap.put("longitude", 0);
                       locationMap.put("latitude", 0);
                   }
               }
               locationMap.put("cdate",System.currentTimeMillis());

               String sign=TransformManager.sortMapByKey(locationMap);

               locationMap.put("sign", sign);

               okHttpClientManager.post(Contants.UPLOADGPS_URL, locationMap, new OkHttpClientManager.okHttpCallback() {
                   @Override
                   public void onFailure(Response<String> s) {
                       LogUtils.e(TAG,"onFailure +"+s.body());
                       ConfigureLog4JUtil.getInstall().printLogger( "postLocation onFailure"+ s.body());
                   }

                   @Override
                   public void onResponse(Response<String> s) {
                       LogUtils.e(TAG,"onResponse +"+s.body());
                       ConfigureLog4JUtil.getInstall().printLogger( "postLocation onResponse"+ s.body());
                   }
               });
           }
       }
    }

    private void acquireWakeLock(){
        if (mWakeLock == null) {
            PowerManager powerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
            mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AmitekAdapter");
        }
        if (mWakeLock != null) {
            mWakeLock.acquire(1000*60*4);
            LogUtils.e(TAG, "acquire powermanager wakelock!");
        }
    }

    public void releaseWakeLock() {
        try {
            if (mWakeLock != null) {
                mWakeLock.release();
                LogUtils.e(TAG, "release powermanager wakelock!");
            }
        }catch (Exception e){
            e.printStackTrace();
            LogUtils.e(TAG, "release powermanager wakelock!"+e.toString());
        }
    }

    private void registerReceiver(){
       if(mAlarmBroadcastReceiver==null)mAlarmBroadcastReceiver=new AlarmBroadcastReceiver();
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction(ACTION_RTC_LOCATION);
        intentFilter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
        intentFilter.addAction("android.intent.action.SCREEN_OFF");
        intentFilter.addAction("android.intent.action.SCREEN_ON");
        intentFilter.addAction("android.intent.action.USER_PRESENT");
        mContext.registerReceiver(mAlarmBroadcastReceiver,intentFilter);
    }

    private void unregisterReceiver(){
        try{
            if(mAlarmBroadcastReceiver!=null) mContext.unregisterReceiver(mAlarmBroadcastReceiver);
        }catch (Exception e){

        }
    }



    private class AlarmBroadcastReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
           if(intent.getAction()==null) return;
            ConfigureLog4JUtil.getInstall().printLogger("AlarmBroadcastReceiver intent"+intent.getAction());
            if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {    //屏幕关闭启动1像素Activity
                Intent it = new Intent(context, OnePiexlActivity.class);
                it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(it);
            } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {   //屏幕打开 结束1像素
                context.sendBroadcast(new Intent(OnePiexlActivity.ACTION_STOP));
//                Intent main = new Intent(Intent.ACTION_MAIN);
//                main.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                main.addCategory(Intent.CATEGORY_HOME);
//                context.startActivity(main);
            }


        }
    };

}
